package com.don.beetl.ext.fn;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.beetl.core.Context;
import org.beetl.core.Function;

/**
 * 开发调试函数接口
 * <p>
 * 功能说明：实现类似php var_dump函数的效果，方便在Web调试beetl模版全局变量及用户变量
 * </p>
 * 
 * @author don
 * @date 2014-10-31
 *       <p>
 * @注 1.发现fastjson转换bug 有XML格式会出现，需要避开显示XML<br>
 *    2.变量不能出现HttpServletRequest对象 fastjson转换会出现java.lang.IllegalStateException:
 *    getInputStream() has already been called for this request问题
 *    </p>
 * @see http://krumo.sourceforge.net
 * @see https://github.com/alibaba/fastjson
 */
public class DevelGlobalVar implements Function {

	private final String PARAM_PREFIX = "paras_";

	public String call(Object[] paras, Context ctx) {
		Map vars = ctx.globalVar == null ? new LinkedHashMap() : ctx.globalVar;
		if (paras != null && paras.length > 0) {// 只打印指定变量
			for (int i = 0; i < paras.length; i++) {
				vars.put(PARAM_PREFIX + i, paras[i]);
			}
		}
		DevelInfo devel = new DevelInfo();
		devel.removeNoSupportVar(vars);
		try {
			ctx.byteWriter.writeString(devel.printJsonObject(vars));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

}
